﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OCR.OCRForm
{
    public partial class SetKey : Form
    {
        public string FormText;
        public string Lable2Text;
        public SetKey()
        {
            InitializeComponent();
        }
        private void SetKey_Load(object sender, EventArgs e)
        {
            if (FormText!="")
            {
                this.Text = FormText;
                label2.Text = Lable2Text;
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Trim() != "" && textBox2.Text.Trim() != "")
            {
                switch (this.Text)
                {
                    case "文字识别":
                        SetValue("OCRClientId", "OCRClientSecret");
                        this.Close();
                        break;
                    case "文本翻译":
                        SetValue("TranslateClientId", "TranslateClientSecret");
                        this.Close();
                        break;
                    default:
                        break;
                }
            }
        }
        public void SetValue(string AppKey, string AppSecret)
        {
            System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
            xDoc.Load(System.Windows.Forms.Application.ExecutablePath + ".config");

            System.Xml.XmlNode xNode;
            System.Xml.XmlElement xElem1;
            System.Xml.XmlElement xElem2;
            xNode = xDoc.SelectSingleNode("//appSettings");

            xElem1 = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
            xElem2 = (System.Xml.XmlElement)xNode.SelectSingleNode("//add[@key='" + AppSecret + "']");
            if (xElem1 != null) 
            { 
                xElem1.SetAttribute("value",textBox1.Text);
                xElem2.SetAttribute("value", textBox2.Text);
            }
            else
            {
                xElem1 = xDoc.CreateElement("add");
                xElem1.SetAttribute("key", AppKey);
                xElem1.SetAttribute("value", textBox1.Text);
                xNode.AppendChild(xElem1);

                xElem2 = xDoc.CreateElement("add");
                xElem2.SetAttribute("key", AppSecret);
                xElem2.SetAttribute("value", textBox2.Text);
                xNode.AppendChild(xElem2);
            }
            xDoc.Save(System.Windows.Forms.Application.ExecutablePath + ".config");
            MessageBox.Show("已保存，请关掉应用重新打开", "提示");
        }
    }
}
